package com.circle.rest.modular.sys.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.circle.rest.core.aop.Log;
import com.circle.rest.core.aop.Permission;
import com.circle.rest.core.common.enums.BusinessType;
import com.circle.rest.core.common.model.SuccessResponseData;
import com.circle.rest.core.common.page.PageInfoBT;
import com.circle.rest.core.exception.ServiceException;
import com.circle.rest.core.jwt.JwtUtil;
import com.circle.rest.core.util.RedisUtil;
import com.circle.rest.core.util.ToolUtil;
import com.circle.rest.modular.sys.dto.UserDto;
import com.circle.rest.modular.sys.model.User;
import com.circle.rest.modular.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author 赵航
 * @since 2019-03-05
 */
@Api(value = "用户信息", tags = {"sys : 用户信息API"})
@RestController
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 查询用户信息列表
     */
    @ApiOperation("查询用户信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "起始数据下标", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "数据条数", dataType = "int"),
            @ApiImplicitParam(name = "condition", value = "手机号/用户名/邮箱/真实姓名/昵称", dataType = "String"),
            @ApiImplicitParam(name = "deptid", value = "部门编号", dataType = "String")
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @Log(title = "查询用户信息列表", businessType = BusinessType.SELECT_LIST)
    @Permission
    public Object list(Integer index, Integer size, String condition, String deptid) {
        Page<User> page = new Page<>(index == null ? 1 : index, size == null ? 15 : size);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (ToolUtil.isNotEmpty(condition)) {
            wrapper = wrapper.like("login_name", condition)
                    .or().like("login_phone", condition)
                    .or().like("login_email", condition)
                    .or().like("real_name", condition)
                    .or().like("nickname", condition);
        }
        if (ToolUtil.isNotEmpty(deptid)) {
            wrapper = wrapper.like("deptid", deptid);
        }
        IPage<User> page1 = userService.page(page, wrapper);

        return new SuccessResponseData(new PageInfoBT<>(page1));
    }

    /**
     * 添加用户信息
     */
    @ApiOperation("添加用户信息")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @Log(title = "添加用户信息", businessType = BusinessType.INSERT)
    @Permission
    public Object add(User user) {
        if (ToolUtil.isEmpty(user.getPassword())) {
            throw new ServiceException("密码不能为空");
        }
        if (ToolUtil.isEmpty(user.getLoginName()) && ToolUtil.isEmpty(user.getLoginPhone()) && ToolUtil.isEmpty(user.getLoginEmail())) {
            throw new ServiceException("用户名、手机号、邮箱至少填写一个");
        }
        if (ToolUtil.isNotEmpty(user.getLoginEmail()) && !ToolUtil.isEmail(user.getLoginEmail())) {
            throw new ServiceException("请输入正确的邮箱");
        }
        if (ToolUtil.isNotEmpty(user.getLoginPhone()) && !ToolUtil.isPhone(user.getLoginPhone())) {
            throw new ServiceException("请输入正确的手机号");
        }
        Wrapper<User> wrapper = new QueryWrapper<User>().lambda()
                .and(i -> i.eq(User::getLoginName, user.getLoginName())
                        .or().eq(User::getLoginPhone, user.getLoginPhone())
                        .or().eq(User::getLoginEmail, user.getLoginEmail())
                );

        List<User> list = userService.list(wrapper);
        if (list.size() > 0) {
            throw new ServiceException("用户信息已存在");
        }
        user.setSalt(ToolUtil.getRandomString(6));
        String password = ToolUtil.md5(user.getPassword(), user.getSalt());
        user.setPassword(password);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        boolean save = userService.save(user);
        return new SuccessResponseData(save);
    }

    /**
     * 修改用户信息
     */
    @ApiOperation("修改用户信息")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @Log(title = "修改用户信息", businessType = BusinessType.UPDATE)
    @Permission
    public Object edit(User user) {
        if (ToolUtil.isEmpty(user.getId())) {
            throw new ServiceException("编号不能为空");
        }
        if (ToolUtil.isEmpty(user.getVersion())) {
            throw new ServiceException("版本号不能为空");
        }
        User userOld = userService.getById(user.getId());
        if (ToolUtil.isEmpty(userOld)) {
            throw new ServiceException("用户信息不存在，更新失败");
        }
        user.setUpdateTime(LocalDateTime.now());
        if (!userService.updateById(user)) {
            throw new ServiceException("乐观锁，更新失败");
        }
        return new SuccessResponseData();
    }

    /**
     * 删除用户信息
     */
    @ApiOperation("删除用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户信息编号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @Log(title = "删除用户信息", businessType = BusinessType.DELETE)
    @Permission
    public Object delete(String id) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException("用户编号不能为空");
        }
        User userOld = userService.getById(id);
        if (ToolUtil.isEmpty(userOld)) {
            throw new ServiceException("用户信息不存在，删除失败");
        }
        if (!userService.removeById(id)) {
            throw new ServiceException("删除失败");
        }
        return new SuccessResponseData();
    }

    /**
     * 查询用户信息
     */
    @ApiOperation("查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户信息编号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @Log(title = "查询用户信息", businessType = BusinessType.SELECT_ONE)
    @Permission
    public Object detail(String id) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException("用户编号不能为空");
        }
        User user = userService.getById(id);
        if (ToolUtil.isEmpty(user)) {
            throw new ServiceException("用户信息不存在");
        }
        return new SuccessResponseData(user);
    }

    @ApiOperation("授权登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "登录名/手机号/邮箱", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @Log(title = "授权登录", businessType = BusinessType.LOGIN)
    public Object login(String userName, String password) {
        if (ToolUtil.isOneEmpty(ToolUtil.trim(userName), ToolUtil.trim(password))) {
            throw new ServiceException("参数不能为空");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (ToolUtil.isPhone(userName)) {
            wrapper = wrapper.eq("login_phone", userName);
        } else if (ToolUtil.isEmail(userName)) {
            wrapper = wrapper.eq("login_email", userName);
        } else {
            wrapper = wrapper.eq("login_name", userName);
        }

        User user = userService.getOne(wrapper);

        if (ToolUtil.isEmpty(user)) {
            throw new ServiceException("用户信息不存在");
        }
        if (!ToolUtil.verify(password, user.getSalt(), user.getPassword())) {
            throw new ServiceException("用户名或者密码不正确");
        }

        String jwt = JwtUtil.generateToken(user);
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwt);

        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        map.put("user", userDto);

        return new SuccessResponseData(map);
    }

    @ApiOperation("注销登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户编号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @Log(title = "注销登录", businessType = BusinessType.LOGOUT)
    public Object logout(String userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException("用户编号不能为空");
        }
        RedisUtil.del("JWT-TOKEN:" + userId);
        return new SuccessResponseData();
    }
}
